package com.foomia.truegoed.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.foomia.truego.Truego;
import com.foomia.truego.parsers.json.Parser;
import com.foomia.truego.types.TruegoType;
import com.foomia.truegoed.error.TruegoCredentialsException;
import com.foomia.truegoed.error.TruegoException;
import com.foomia.truegoed.error.TruegoParseException;


public class JSONUtils {
	private static final boolean DEBUG = Truego.DEBUG;
    private static final Logger LOG = Logger.getLogger(JSONUtils.class.getCanonicalName());
    
    /**
     * Takes a parser, a json string, and returns a Truego type.
     */
    public static TruegoType consume(Parser<? extends TruegoType> parser, String content)
        throws TruegoCredentialsException, TruegoParseException, TruegoException, IOException {
        
        if (DEBUG) {
            LOG.log(Level.FINE, "http response: " + content);
        }
        
        try {
        	// The v1 API returns the response raw with no wrapper. Depending on the
            // type of API call, the content might be a JSONObject or a JSONArray.
            // Since JSONArray does not derive from JSONObject, we need to check for
            // either of these cases to parse correctly.
            JSONObject json = new JSONObject(content);
            Iterator<String> it = (Iterator<String>)json.keys();
            if (it.hasNext()) {
                //String key = (String)it.next();
            	//String status=json.getString("status");
                //if (!status.equals("OK")) {
                    
                	//throw new TruegoException(status);
                //} else {
                	Object obj=null;
                	if(json.has("results")){
                		obj = json.get("results");
                	}
                	else if(json.has("result")){
                		obj = json.get("result");
                	}
                	
                	else if(json.has("posts")){
                		obj = json.get("posts");
                	}
                	
                	else if(json.has("deals")){
                		obj = ((JSONObject)json.get("deals")).get("deal");
                	}
                	
                    if (obj instanceof JSONArray) {
                        return parser.parse((JSONArray)obj);
                    } else {
                        return parser.parse((JSONObject)obj);
                    }
                //}
            } else {
                throw new TruegoException("Error parsing JSON response, object had no single child key.");
            }
            
        } catch (JSONException ex) {
            throw new TruegoException("Error parsing JSON response: " + ex.getMessage());
        }
    }

}
